<template>
  <div class="c-bg-sgray">
    <my-small-tabbar id="tab-bar" class="c-bg-white" :isNew='true' :tabList="tabList" :tabIndex="searchType" @changeTab="changeType"></my-small-tabbar>
    <new-search-bar class="c-bg-white c-pb10" @search="startSearch" @cancel="startSearch" v-if="searchType == 1"></new-search-bar>
    <div class="c-ph24 c-pt24">
      <div class="c-flex-column c-mb16 c-bg-white c-br16" v-for="(item,index) in clockInList" :key="index">
        <div class="c-ph20 c-flex-row c-bd-b1 c-pv30 c-p" @click="clickGoClockInDetail(item)">
          <div class="open-tag-wrap" v-if="enableCenter">
            <wx-open-launch-weapp
              class="launch-btn"
              :appid="`${appid}`"
              :username="username"
              :path="`${path}?${item.wxappQuery}`"
              @error="handleErrorFn"
              @launch="handleLaunch"
            >
              <script type="text/wxtag-template">
                <!-- 这里是为了撑开元素，让其可以被点击，不添加template会报错，添加了template不添加内容也会报错 -->
                <div style="padding: 10000px">
                </div>
              </script>
            </wx-open-launch-weapp>
          </div>
          <div class="c-ww180 c-hh120 c-text-hidden c-p c-br16" :class="themeName == 'mb3' ? 'c-br10' : ''">
            <CoverImg :coverSizeClass="'c-w100 c-h c-br16 c-text-hidden'" imgClass="c-br16" :coverUrl="$addXossFilter(item.cover, require('../../../assets/defult270.png'))" />
            <!-- <img class="c-w100" :src="$addXossFilter(item.cover)" alt="" /> -->
          </div>
          <div class="c-flex-column c-ml20 c-justify-sb">
            <div class="c-fs24 c-text-ellipsis2 c-ww320 c-fw600">{{item.name}}</div>
            <div v-if="item.type == 2" class="c-flex-row c-aligni-center c-pt30">
              <span class="c-fs20 c-fc-gray">作业数{{item.hasWorks}}个</span>
              <span class="c-ph8 c-fs20 c-fc-gray">|</span>
              <span class="c-fs20 c-fc-gray">已提交{{item.hasFinish}}个</span>
            </div>
            <div v-else-if="item.type == 1" class="c-flex-row c-aligni-center c-pt30">
              <span class="c-fs20 c-fc-gray">已进行{{item.nowDayNum}}天</span>
              <span class="c-ph8 c-fs20 c-fc-gray">|</span>
              <span class="c-fs20 c-fc-gray">已打卡{{item.hasFinish}}天</span>
            </div>
            <div v-else class="c-flex-row c-aligni-center c-pt30">
              <span class="c-fs20 c-fc-gray">总课时{{item.courseNum}}课</span>
              <span class="c-ph8 c-fs20 c-fc-gray">|</span>
              <span class="c-fs20 c-fc-gray">已完成{{item.hasFinish}}课</span>
            </div>
          </div>
        </div>
        <div class="c-flex-row c-flex-center c-pv24 c-fs22">
          <div class="c-w0 c-flex-grow1 c-bd-r1 c-textAlign-c" @click="clickGoRank(index)">排行榜</div>
          <div class="c-w0 c-flex-grow1 c-bd-r1 c-textAlign-c" @click="clickInviteFriend(item.signColId)">邀请卡</div>
          <!-- <div v-if="item.type == 2" class="c-w0 c-flex-grow1 c-textAlign-c" @click="clickEnterCourse(index)">作业本</div>
          <div v-else-if="item.type == 1" class="c-w0 c-flex-grow1 c-textAlign-c" @click="clickEnterCalendar(index, item.isTeacher)">打卡日历</div>
          <div v-else class="c-w0 c-flex-grow1 c-textAlign-c" @click="clickEnterLevel(index)">课时表</div> -->
        </div>

      </div>
      <loading-status-tem :dataStatus="dataStatus" noDataText="暂无打卡"></loading-status-tem>
    </div>
  </div>
</template>

<script>
import newSearchBar from "@/components/templates/common/newSearchBar.vue"
import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import CoverImg from '@/components/templates/common/coverImg.vue';
import {
  utilJs
} from "@/utils/common.js";
let pageIndex = 0;
let LIMIT = 10;
export default {
  name: "MyClockInList",
  components: {
    loadingStatusTem,
    newSearchBar,
    MySmallTabbar,
    CoverImg
  },
  props: [],
  data() {
    return {
      theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
      themeName: localStorage.getItem('themeName') ? localStorage.getItem('themeName') : 'mb5',
      dataStatus: 'HAS_MORE_DATA',
      searchName: '',
      clockInList: [],
      tabList:[
        {
          title: '最近参与',
          index: 1,
        },
        {
          title: '最近浏览',
          index: 2,
        }
      ],
      searchType: 1,
      showAialogPop : false, //是否弹窗提醒：true=是；false=否
      enableBanner: 0, //是否横幅提醒：1=是；0=否
      enableCenter:0, //是否互动入口跳转小程序：1=是；0=否
      appid:'wxc99b13f1a0b51048',
      path:'/pages/clockIn/homeWorker/index'
    };
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() { },
  methods: {
    handleLaunch(e) {
        console.log('handleLaunch---', e)
        // this.$emit('handleLaunch')
    },
    handleErrorFn(e) {
      this.$showCjToast({
        text: e.errMsg || '无法打开小程序，请升级微信版本',
        type: "warn",
        time: 1500
      })
    },
    appletInletInfo() {
      utilJs.getMethod(
        `${global.apiurl}signCard/appletInletInfo`,
        (res) => {
          if (!utilJs.isWeiXin()) {
            return
          }
          // enablePop是否弹窗提醒：1=是；0=否
          if (res.enablePop == 1 && res.enableAppletRemind == 1) {
            this.showAialogPop = true
          }
          // enableBanner是否横幅提醒：1=是；0=否
          this.enableBanner = res.enableBanner
          // enableCenter是否个人中心进入打卡小程序：1=是；0=否
          this.enableCenter = res.enableCenter
        }
      );
    },
    changeType(tabIndex) {
      if (this.searchType != tabIndex) {
        pageIndex = 1;
        this.clockInList = [];
        this.searchType = tabIndex;
        this.searchName = ''
        this.getClockInList();
      }
    },
    //邀请好友
    clickInviteFriend(signColId) {
      this.$routerGo(this, "push", {
        path: "/homePage/spread/spreadCustom",
        query: {
          extId: signColId,
          cId: 0,
          ckFrom: global.ckFrom.clockIn,
        }
      });
    },
    //排行榜
    clickGoRank(index) {
      let signColId = this.clockInList[index].signColId;
      let title = this.clockInList[index].name;
      let shareImg = this.clockInList[index].cover;
      let shareUrl =
        window.location.href.split("#")[0] +
        "#/homePage/clockIn/clockInDetail?clockInId=" +
        signColId +
        "&refereeId=" +
        localStorage.getItem("userId");

      let shareDesc = "点击查看详情";
      let shareData = {
        title: title,
        shareImg: shareImg,
        shareUrl: shareUrl,
        shareDesc: shareDesc
      };
      localStorage.setItem("homeWorkShareInfo", JSON.stringify(shareData));

      this.$routerGo(this, "push", {
        path: "/homePage/clockIn/rankList",
        query: {
          clockId: signColId,
          setScore: 3
        }
      });
    },
    //开始搜索
    startSearch(e) {
      this.searchName = e.searchValue;
      pageIndex = 1;
      this.getClockInList();
    },
    clickGoClockInDetail(clockInInfo) {
      if (this.enableCenter) {
        return
      }
      let title = clockInInfo.name;
      let shareImg = clockInInfo.cover;
      let shareUrl = `${window.location.href.split("#")[0]}#/homePage/clockIn/clockInDetail?clockInId=${clockInInfo.signColId}&refereeId=${localStorage.getItem("userId")}`;
      let shareDesc = clockInInfo.shareDesc || "点击查看详情";
      let shareData = {
        title: title,
        shareImg: shareImg,
        shareUrl: shareUrl,
        shareDesc: shareDesc
      };
      localStorage.setItem("homeWorkShareInfo", JSON.stringify(shareData));
      // if (clockInInfo.isTeacher == 1) {
      //   this.$routerGo(this, "push", {
      //     path: `/homePage/clockIn/teaHomeWorker?fromDetail=1&clockInId=${clockInInfo.signColId}`
      //   });
      //   return
      // }
      switch (clockInInfo.type) {
        case 1:
          //日历打卡,若当前日期不在开始日期和结束日期之间，则从开始日期进入，否则从当前日期进入
          let startTimeTamp = new Date(`${clockInInfo.startTime} ${clockInInfo.startHour}`.replace(/-/g, "/")).getTime();
          let endTimeTamp = new Date(`${clockInInfo.endTime} ${clockInInfo.endHour}`.replace(/-/g, "/")).getTime();
          let nowTimeTamp = new Date().getTime();
          let curTime = utilJs.dateFormat(nowTimeTamp);
          if (nowTimeTamp < startTimeTamp || nowTimeTamp > endTimeTamp) {
            curTime = clockInInfo.startTime;
          }
          console.log(curTime)
          this.$routerGo(this, "push", {
            path: `/homePage/clockIn/stuHomeWork?workType=1&clockInId=${clockInInfo.signColId}&curDate=${curTime}`
          });
          break;
        case 2:
          //作业打卡，如果超过一个作业，则进入作业列表，否则进入作业详情
          let nextUrl = `/homePage/clockIn/stuHomeWork?workType=2&clockInId=${clockInInfo.signColId}&curId=${clockInInfo.hwId}`;
          this.$routerGo(this, "push", {
            path: nextUrl
          });
          break;
        case 3:
          //闯关打卡
          this.$routerGo(this, "push", {
            path: `/homePage/clockIn/stuHomeWork?workType=3&clockInId=${clockInInfo.signColId}&curId=${clockInInfo.hwId}`
          });
          break;
      }
    },

    //直接进入打卡
    clickEnterCourse(index) {
      let signColId = this.clockInList[index].signColId;
      let hwId = this.clockInList[index].hwId;
      if (hwId == 0) {
        let title = this.clockInList[index].name;
        let shareImg = this.clockInList[index].cover;
        let shareUrl =
          window.location.href.split("#")[0] +
          "#/homePage/clockIn/clockInDetail?clockInId=" +
          signColId +
          "&refereeId=" +
          localStorage.getItem("userId");

        let shareDesc = "点击查看详情";
        let shareData = {
          title: title,
          shareImg: shareImg,
          shareUrl: shareUrl,
          shareDesc: shareDesc
        };
        localStorage.setItem("homeWorkShareInfo", JSON.stringify(shareData));
        this.$routerGo(this, "push", {
          path: "/homePage/clockIn/homeWorkList?clockInId=" + signColId
        });
      } else {
        this.$routerGo(this, "push", {
          path: "/homePage/clockIn/stuHomeWork?workType=2&clockInId=" + signColId + '&curId=' + hwId
        });
      }
    },
    //直接进入日历打卡
    clickEnterCalendar(index, isTeacher) {
      let signColId = this.clockInList[index].signColId;
      let title = this.clockInList[index].name;
      let shareImg = this.clockInList[index].cover;
      let shareUrl =
        window.location.href.split("#")[0] +
        "#/homePage/clockIn/clockInDetail?clockInId=" +
        signColId +
        "&refereeId=" +
        localStorage.getItem("userId");

      let shareDesc = "点击查看详情";
      let shareData = {
        title: title,
        shareImg: shareImg,
        shareUrl: shareUrl,
        shareDesc: shareDesc
      };
      localStorage.setItem("homeWorkShareInfo", JSON.stringify(shareData));
      this.$routerGo(this, "push", {
        path: "/homePage/clockIn/clockCalendar",
        query: {
          clockInId: signColId,
          fromMember: 1,
          isTeacher: isTeacher
        }
      });
    },
    //进入闯关打卡课时表
    clickEnterLevel(index) {
      let signColId = this.clockInList[index].signColId;
      let title = this.clockInList[index].name;
      let shareImg = this.clockInList[index].cover;
      let shareUrl =
        window.location.href.split("#")[0] +
        "#/homePage/clockIn/clockInDetail?clockInId=" +
        signColId +
        "&refereeId=" +
        localStorage.getItem("userId");

      let shareDesc = "点击查看详情";
      let shareData = {
        title: title,
        shareImg: shareImg,
        shareUrl: shareUrl,
        shareDesc: shareDesc
      };
      localStorage.setItem("homeWorkShareInfo", JSON.stringify(shareData));
      this.$routerGo(this, "push", {
        path: "/homePage/clockIn/levelList?clockInId=" + signColId
      });
    },

    //获取我的作业列表
    getClockInList() {
      if (this.dataStatus == 'LOADING') {
        return;
      }
      this.dataStatus = 'LOADING';
      utilJs.getMethod(
        global.apiurl + "signCard/mySignCard?page=" + pageIndex + '&limit=' + LIMIT + '&searchName=' + this.searchName + '&searchType=' + this.searchType,
        res => {
          if (pageIndex == 1) {
            this.clockInList = res.data;
          } else {
            this.clockInList = [...this.clockInList, ...res.data];
          }
          if (res.data && (res.data.length < LIMIT)) {
            this.dataStatus = pageIndex == 1 && res.data.length == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
          } else {
            this.dataStatus = 'HAS_MORE_DATA';
            pageIndex++;
          }
          for (let item in this.clockInList) {
            console.log(item)
            if (this.clockInList[item].type == 1) {
              //日历打卡,若当前日期不在开始日期和结束日期之间，则从开始日期进入，否则从当前日期进入
              let startTimeTamp = new Date(`${this.clockInList[item].startTime} ${this.clockInList[item].startHour}`.replace(/-/g, "/")).getTime();
              let endTimeTamp = new Date(`${this.clockInList[item].endTime} ${this.clockInList[item].endHour}`.replace(/-/g, "/")).getTime();
              let nowTimeTamp = new Date().getTime();
              let curTime = utilJs.dateFormat(nowTimeTamp);
                //日历打卡,若当前日期不在开始日期和结束日期之间，则从开始日期进入，否则从当前日期进入
              if (nowTimeTamp < startTimeTamp || nowTimeTamp > endTimeTamp) {
                curTime = this.clockInList[item].startTime;
              }
              this.clockInList[item].wxappQuery = `workType=1&fromDetail=1&cId=${localStorage.getItem("companyId")}&clockInId=${this.clockInList[item].signColId}&curSelectDate=${curTime}`
            } else if (item.type == 2) {
              this.clockInList[item].wxappQuery = `workType=2&fromDetail=1&cId=${localStorage.getItem("companyId")}&clockInId=${this.clockInList[item].signColId}&curId=${this.clockInList[item].hwId}`
            } else {
              this.clockInList[item].wxappQuery = `workType=3&fromDetail=1&cId=${localStorage.getItem("companyId")}&clockInId=${this.clockInList[item].signColId}&curId=${this.clockInList[item].hwId}`
              //闯关打卡
            }
          }
        },
        failRes => {
          this.dataStatus = 'DATA_ERROR';
        }
      );
    },
    //分享
    wechatShare: function () {
      let shareUrl =
        window.location.href.split("#")[0] +
        "#" +
        this.$route.path +
        "?refereeId=" +
        localStorage.getItem("userId");
      utilJs.wechatConfig(shareUrl, "我的打卡", "", "", function () { });
    },
    //手机端分享
    appShare: function () {
      let shareUrl =
        window.location.href.split("#")[0] +
        "#" +
        this.$route.path +
        "?refereeId=" +
        localStorage.getItem("userId");
      utilJs.appShareTrue("我的打卡", "", shareUrl, "");
    },
    windowScrollFunction() {
      utilJs.handleLoading(() => {
        if (this.dataStatus == 'HAS_MORE_DATA' && this.clockInList.length > 0) {
          this.getClockInList();
        }
      });
    },
    initData() {
      pageIndex = 1;
      this.dataStatus = 'HAS_MORE_DATA';
      this.searchName = '';
      this.clockInList = [];
      this.searchType = 1
      this.getClockInList();
    },
  },
  activated() {
    setDocumentTitle("我的打卡");// eslint-disable-line
    if (utilJs.checkNeedInitData(this.clockInList, pageIndex)) {
      this.initData()
    }
    this.wechatShare();
    this.appletInletInfo()
    window.addEventListener('scroll', this.windowScrollFunction);
  },
  deactivated() {
    // this.dataStatus = 'NO_MORE_DATA';
    window.removeEventListener('scroll', this.windowScrollFunction);
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.open-tag-wrap {
  position: absolute;
  z-index: 10;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: transparent;
}
.launch-btn {
  width: 100%;
  height: 100%;
  display: block;
  overflow: hidden;
}
</style>
